package com.ciaojian.bytedance.service;

import cn.hutool.core.collection.CollUtil;
import com.ciaojian.bytedance.policy.impl.coupon.CodeDiscount;
import com.ciaojian.bytedance.policy.impl.coupon.MemberCardDiscount;
import com.ciaojian.bytedance.policy.impl.coupon.ShoudanDiscount;
import com.ciaojian.core.model.Order;
import com.ciaojian.core.service.ICouponDiscount;
import com.ciaojian.core.util.ApplicationContextHelper;
import com.ciaojian.core.util.LogUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl {

    @Transactional(rollbackFor = Exception.class)
    public BigDecimal calDiscountV2(Order order, List<String> codes, String type, Integer memberDiscountId, BigDecimal money, Integer userIdOfOrder) throws JsonProcessingException {
        BigDecimal amount;
        // 首单优惠 id 不为空
        if (memberDiscountId != null) {
            LogUtil.writeBusinessLog(">>>calDiscount>>>用户[{}]有首单优惠id[{}]", userIdOfOrder, memberDiscountId);
            // 首单优惠
            ICouponDiscount<Map<String, Object>> couponDiscount = ApplicationContextHelper.getBean(ShoudanDiscount.class);
            Map<String, Object> shoudanMap = new HashMap<>(2);
            shoudanMap.put("memberDiscountId", memberDiscountId);
            shoudanMap.put("userIdOfOrder", userIdOfOrder);
            amount = couponDiscount.discountAmount(shoudanMap, money);
        }
        // 使用优惠券
        else if (CollUtil.isNotEmpty(codes)) {
            LogUtil.writeBusinessLog(">>>calDiscount>>>用户[{}]有优惠券码[{}]", userIdOfOrder, codes.toString());
            ICouponDiscount<Map<String, Object>> codeDiscount = ApplicationContextHelper.getBean(CodeDiscount.class);
            Map<String, Object> codeMap = new HashMap<>(2);
            codeMap.put("code", codes);
            codeMap.put("userId", userIdOfOrder);
            codeMap.put("order", order);
            amount = codeDiscount.discountAmount(codeMap, money);
        }
        // 会员折扣
        else {
            LogUtil.writeBusinessLog(">>>calDiscount>>>用户[{}]有会员折扣", userIdOfOrder);
            ICouponDiscount<Map<String, Object>> memberCardDiscount = ApplicationContextHelper.getBean(MemberCardDiscount.class);
            Map<String, Object> memberMap = new HashMap<>(2);
            memberMap.put("userId", userIdOfOrder);
            memberMap.put("type", type);
            amount = memberCardDiscount.discountAmount(memberMap, money);
        }
        return amount;
    }
}
